1. Introduction to CSS Grid Layout
CSS Grid Layout is a powerful two-dimensional layout system that allows you to create complex, responsive layouts with rows and columns. It provides precise control over the placement and sizing of elements, making it ideal for modern web design.
Key features of CSS Grid:
- Create layouts with rows and columns.
- Align items both horizontally and vertically.
- Control spacing between items using gaps.
- Responsive design with minimal code.
Grid Layout consists of two main components:
- Grid Container: The parent element that holds grid items.
- Grid Items: The child elements inside the grid container.
2. Creating a Grid Container
To create a grid container, set the display property to grid or inline-grid.
.container {
display: grid; /* Creates a grid container */
}
Once the container is defined, you can use properties like grid-template-columns, grid-template-rows, and grid-gap to define the layout.
3. Defining Columns and Rows
Use grid-template-columns and grid-template-rows to define the structure of the grid.
.container {
grid-template-columns: 100px 200px 100px; /* Three columns */
grid-template-rows: 100px 200px; /* Two rows */
}
You can also use the repeat() function to simplify repetitive values:
.container {
grid-template-columns: repeat(3, 1fr); /* Three equal-width columns */
grid-template-rows: repeat(2, 100px); /* Two rows of 100px height */
}
4. Adding Gaps Between Items
The grid-gap property defines the spacing between rows and columns.
.container {
grid-gap: 10px; /* 10px gap between rows and columns */
}
You can also specify separate gaps for rows and columns:
.container {
grid-row-gap: 20px; /* 20px gap between rows */
grid-column-gap: 15px; /* 15px gap between columns */
}
5. Aligning Items in the Grid
Use justify-items and align-items to align items within their grid cells.
.container {
justify-items: center; /* Center items horizontally */
align-items: center; /* Center items vertically */
}
Other values for alignment include:
- start: Align items to the start of the cell.
- end: Align items to the end of the cell.
- stretch: Stretch items to fill the cell.
6. Placing Items in Specific Cells
You can place grid items in specific rows and columns using the grid-column and grid-row properties.
.item {
grid-column: 1 / 3; /* Item spans from column 1 to column 3 */
grid-row: 1 / 2; /* Item spans from row 1 to row 2 */
}
You can also use the span keyword to define how many rows or columns an item should span:
.item {
grid-column: span 2; /* Item spans 2 columns */
grid-row: span 1; /* Item spans 1 row */
}